package com.dongrj.framework.web.utils;

import com.alibaba.excel.EasyExcel;
import com.dongrj.framework.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public final class AliExcelUtils {

    public static <T> void export(String fileName, Class<T> tClass, List<T> data) {
        export(fileName, fileName, tClass, data);
    }

    public static <T> void export(String fileName, String sheetName, Class<T> tClass, List<T> data) {
        EasyExcel.write(fileName, tClass).sheet(sheetName).doWrite(data);
    }

    public static <T> void export(HttpServletResponse response, String fileName, Class<T> tClass, List<T> data) {
        export(response, fileName, fileName, tClass, data);
    }

    public static <T> void export(HttpServletResponse response, String fileName, String sheetName, Class<T> tClass, List<T> data) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileNameEncode = null;
        try {
            fileNameEncode = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameEncode + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            log.error("export.e.head", e);
        }
        if (StringUtils.isEmpty(fileNameEncode)) {
            return;
        }
        try {
            EasyExcel.write(response.getOutputStream(), tClass).sheet(sheetName).doWrite(data);
        } catch (IOException e) {
            log.error("export.e.data", e);
        }
    }

}
